import { ReactElement, useState, useEffect } from 'react'
import style from './index.module.less'
import { Table } from 'antd'
import { getColumn } from './util'
import { awaitWrap } from '@js/tool'
import EditModal from './components/editModal'
import { DataSchema, getListRequest } from './ajax'
import { WorkPerformanceSchema } from '@components/schema/performanceSchema'

async function initList (work: WorkPerformanceSchema | null, workType: string, setList: (v: DataSchema[]) => void, setLoading: (v: boolean) => void): Promise<void> {
  if (work === null) {
    return undefined
  }
  setLoading(true)
  const [e, d] = await awaitWrap(getListRequest(work.id, workType))
  setLoading(false)
  if (e === null && d instanceof Array) {
    setList(d)
  }
}

interface Props {
  workType: string
  work: WorkPerformanceSchema | null
  refreshData: () => void
}

function Main ({ workType, work, refreshData }: Props): ReactElement {
  const [workid, setWorkid] = useState('')
  const [visible, setVisible] = useState(false)
  const [modifyData, setModifyData] = useState<DataSchema | null>(null)
  const [list, setList] = useState<DataSchema[]>([])
  const [loading, setLoading] = useState(false)
  function initData (): void { initList(work, workType, setList, setLoading).catch(e => console.error(e)); refreshData() }
  useEffect(() => {
    if (work !== null && work.id !== workid) {
      setWorkid(work.id)
    }
  }, [work])
  useEffect(() => {
    initList(work, workType, setList, setLoading).catch(e => console.error(e))
  }, [workid])
  return (
    <div>
      <EditModal visible={visible} workType={workType} hide={() => { setVisible(false); setModifyData(null) }} work={work} data={modifyData} refreshData={initData} />
      <div className={style.header}>
        <span className={style['header-title']}>{workType}</span>
        <a className={style['add-btn']} onClick={() => { setModifyData(null); setVisible(true) }}>添加</a>
      </div>
      <Table rowKey='id' columns={getColumn(setVisible, setModifyData, initData)} loading={loading} dataSource={list} />
    </div>
  )
}

export default Main
